#include <ssh/client.h>
SSHClient::SSHClient(const char* host,const char* port,const char*  user,const char*  password):session(nullptr),channel(nullptr) {
    cout << "connect client >> " << this << endl;
    session = ssh_new();
    if (session == NULL)
    {
        cout << "Failed to create SSH session" << endl;
        return;
    }
    ssh_options_set(session, SSH_OPTIONS_PORT_STR, port);
    ssh_options_set(session, SSH_OPTIONS_HOST, host);
    if (ssh_connect(session) != SSH_OK)
    {
        std::cout << "Failed to connect to SSH server" << std::endl;
        ssh_free(session);
        return;
    }
    if (ssh_userauth_password(session, user, password) != SSH_AUTH_SUCCESS)
    {
        cout << "Failed to authenticate" << endl;
        ssh_disconnect(session);
        ssh_free(session);
        return;
    }
    channel = ssh_channel_new(session);
    if (ssh_channel_open_session(channel) != SSH_OK)
    {
        cout << "Failed to open SSH channel" << endl;
        ssh_disconnect(session);
        ssh_free(session);
        if(channel != nullptr){
            ssh_channel_send_eof(channel);
            ssh_channel_close(channel);
            ssh_channel_free(channel);
            channel = nullptr;
            session = nullptr;
            return;
        }
    }
    cout << "connected client >> " << this << endl;
}

SSHClient::~SSHClient()
{
    if (channel != nullptr)
    {
        ssh_channel_send_eof(channel);
        ssh_channel_close(channel);
        ssh_channel_free(channel);
    }
    if (session != nullptr)
    {
        ssh_disconnect(session);
        ssh_free(session);
    }
    channel = nullptr;
    session = nullptr;
}

bool SSHClient::status(){
    if(session != nullptr && channel != nullptr){
        return true;
    }
    return false;
}

ssh_channel SSHClient::get_channel(){
    if(session != nullptr){
        channel = ssh_channel_new(session);
    }
    return channel;
}